﻿using System;
using IQIGame.Onigao.Framework.Serialization;
using IQIGame.Onigao.GamePlay;
using LFloatMath.Math;

namespace IQIGame.Onigao.Logic
{
    public class SkillEffective_ExtendBuffDuration : SkillEffective
    {
        protected override ISerializeCustomPOD OnExecute(SkillEffectiveData data, Unit target, SkillEffectiveContext context, int effectiveIndex, out SkillEffectiveResponse startResp)
        {
            startResp = null;
            if (data.effectiveConfig.customConfig is SkillEffective_ExtendBuffDuration_ConfigData rConfig)
            {
                var rBuffID = rConfig.buffID;
                var rAttacker = context.skill.executer;
                var nBuffID = BattleUtil.GetValue(rBuffID, rAttacker, target, 0);
                var nExtend = BattleUtil.GetValue(rConfig.extend, rAttacker, target, 0);

                this.Extend(rAttacker, target, nBuffID, nExtend);
            }
            return null;
        }

        protected override ISerializeCustomPOD OnActionExecute(SkillEffectiveData data, SkillActionNode action, Unit target, ref SkillEffectiveContext context, int effectiveIndex)
        {
            if (action.customConfig is SkillEffectiveAction_ExtendBuffDuration_ConfigData rConfig)
            {
                var rAttacker = context.skill.executer;
                var nBuffID = rConfig.buffID.GetValue(rAttacker, target, context).ToInt();
                var nExtend = rConfig.extend.GetValue(rAttacker, target, context).ToInt();

                this.Extend(rAttacker, target, nBuffID, nExtend);
            }
            return null;
        }

        private void Extend(Unit rAttacker, Unit rTarget, int nBuffID, int nExtend)
        {
            var rTargetComp = rTarget.GetComponent<BuffComponent>(ETComponentType.BuffComponent);
            var rBuff = rTargetComp.buffList.Find((x) => x.buffID == nBuffID);
            if (rBuff != null && rBuff.timeDuration > 0)
            {
                rBuff.timeDuration = Math.Max(rBuff.timeDuration + nExtend, 0);
            }
        }

#if UNITY_EDITOR
        public override string ToString(SkillCustomConfig config)
        {
            if (config is SkillEffective_Buff_ConfigData rData)
            {
                return $"延长buff持续时间 {(rData.buffID.isFormula ? "公式" : "")} {rData.buffID.value} 层数 " +
                       (rData.stack != null ? $"{(rData.stack.isFormula ? "公式" : "")} {rData.stack.value})" : "1");
            }

            return "延长buff持续时间";
        }
#endif
    }
}